import path from 'path'
import fs from 'fs'
import { createMarkdownRenderer } from 'vitepress'

export interface ExampleData {
  [key: string]: string | ExampleData
}

export declare const data: Record<string, ExampleData>

export default {
  watch: './src/**',
  async load() {
    const md = await createMarkdownRenderer(process.cwd(), {
        theme: 'github-dark',
    }, '/')
    const files = readTutorialSteps(path.resolve(__dirname, './src'))
    for (const step in files) {
      const stepFiles = files[step]
      const desc = stepFiles['description.md'] as string
      if (desc) {
        stepFiles['description.md'] = md.render(desc)
      }
    }
    return files
  }
}

// 重新实现读取教程步骤的函数，避免EISDIR错误
export function readTutorialSteps(srcDir: string): Record<string, ExampleData> {
  const steps = fs.readdirSync(srcDir)
  const data: Record<string, ExampleData> = {}
  
  for (const stepName of steps) {
    const stepPath = path.join(srcDir, stepName)
    // 确保只处理目录
    if (fs.statSync(stepPath).isDirectory()) {
      data[stepName] = readStepContent(stepPath)
    }
  }
  
  return data
}

// 读取单个步骤的内容
function readStepContent(dir: string): ExampleData {
  const filenames = fs.readdirSync(dir)
  const files: ExampleData = {}
  
  for (const filename of filenames) {
    const fullPath = path.join(dir, filename)
    const stats = fs.statSync(fullPath)
    
    if (stats.isDirectory()) {
      // 处理子目录
      if (filename === '_hint') {
        files[filename] = readStepContent(fullPath)
      } else {
        // 处理App和ChildComp等组件目录
        files[filename] = readComponentDir(fullPath)
      }
    } else {
      // 处理文件
      files[filename] = fs.readFileSync(fullPath, 'utf-8')
    }
  }
  
  // 处理_hint目录的回退逻辑
  if ('_hint' in files && typeof files._hint !== 'string') {
    const hintObj = files._hint as ExampleData;
    
    for (const filename in files) {
      if (filename !== '_hint') {
        const fileContent = files[filename];
        
        if (typeof fileContent !== 'string') {
          // 如果不是字符串，说明是一个对象（组件目录等）
          if (!(filename in hintObj)) {
            hintObj[filename] = {};
          }
          
          const hint = hintObj[filename] as ExampleData;
          
          // 只有当两者都是对象时才进行属性合并
          if (typeof hint !== 'string') {
            for (const key in fileContent) {
              if (!(key in hint)) {
                hint[key] = fileContent[key];
              }
            }
          }
        }
      }
    }
  }
  
  return files
}

// 读取组件目录
function readComponentDir(dir: string): Record<string, string> {
  const filenames = fs.readdirSync(dir)
  const files: Record<string, string> = {}
  
  for (const filename of filenames) {
    const filePath = path.join(dir, filename)
    // 确保只读取文件，不读取目录
    if (fs.statSync(filePath).isFile()) {
      let content = fs.readFileSync(filePath, 'utf-8')
      if (!content.endsWith('\n')) content += '\n'
      files[filename] = content
    }
  }
  
  return files
}
